# -*- encoding: utf-8 -*-

from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.contrib.auth import login, logout, authenticate
from verta.libs.default.views import DefaultView
from verta.libs.default.decorators import logged, anonymous

class UserHandler(DefaultView):
    '''Handle user information'''
    def login(self):
        '''User Login'''
        # Try to authenticate user
        user = authenticate(username=self.method['username'], password=self.method['password'])
        # If user is authenticated
        if user:
            # Login user at this session
            login(self.request, user)
            return self.success_message('login')
        # Else print error message
        return self.error_message(msg='Wrong username and/or password')

    def logout(self):
        '''User logout'''
        # Logout session
        logout(self.request)
        return self.success_message('logout')

    def verify(self):
        '''Returns if user NOT exists'''
        if not 'username' in self.method:
            return None

        try:
            User.objects.get(username=self.method['username'])
            return False
        except User.DoesNotExist:
            return True

    def register(self):
        '''TODO: Register user'''
        
        # Required parameters and fields required to register user
        required_fields = ['username', 'password', 'confirmation', 'email']
        # List of missing parameters
        missing = []
        # Verify each required field
        for field in required_fields:
            if field in self.method:
                print self.method
            if not field in self.method or self.method[field].strip() == '':
                missing.append(field)
        # If there are parameters missing, show error message
        if missing:
            return self.error_message(fields=missing)       
        # Verify if user typed password correctly        
        if not self.method['password'] == self.method['confirmation']:
            return self.error_message(msg='Passwords do not match')
        # Treat username
        username = self.treat(self.method['username'])

        # If username exists return error message
        if not self.verify:
            return self.error_message(msg='User already exists')
        
        # Create user
        user = User.objects.create_user(username=username, password=self.method['password'], email=self.method['email'])
        user.save()
        
        return self.success_message('register', username)

def index(request):
    '''Returns User index page'''
    return render_to_response('user/index.html', {})

@anonymous
def verify(request):
    '''Returns if username does NOT exist'''
    handler = UserHandler(request)
    answer = handler.verify()
    if answer == True:
        return handler.success_message('verify user')
    elif answer == False:
        return handler.error_message(msg='User already exists')
    elif answer == None:
        return handler.error_message(msg='You must pass username')

@anonymous
def log_user_in(request):
    return UserHandler(request).login()

@logged
def log_user_out(request):
    return UserHandler(request).logout()

@anonymous
def register(request):
    return UserHandler(request).register()        

